import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

import { BaseDirective } from '../../../core/models/base-directive.model';

declare const $: any;

/**
 * Bootstrap material date picker. If the minDate or maxDate provided, the UI will hide 
 * the according month and year selection. This is by design, NOT a bug.
 */
@Component({
    selector: 'op-material-date-picker',
    templateUrl: './material-date-picker.component.html'
})
export class MaterialDatePickerComponent extends BaseDirective implements AfterViewInit, OnInit {
    @Input() fieldClass: string = 'form-control';
    @Input() format: string = 'YYYY-MM-DD';
    @Input() minDate: string;
    @Input() maxDate: string;
    @Input() showDate: boolean = true;
    @Input() showTime: boolean = false;
    @Input() selectedValue: string;
    @Output() selectedValueChange: EventEmitter<string> = new EventEmitter<string>();
    dateId: string;

    constructor() {
        super();
    }

    ngOnInit(): void {
        super.ngOnInit();

        this.dateId = this.generatePanelBodyId('dateId');
    }

    ngAfterViewInit(): void {
        $(`#${this.dateId}`).bootstrapMaterialDatePicker({
            weekStart: 0,
            lang: 'zh-cn',
            format: this.format,
            time: this.showTime,
            minDate: this.minDate,
            maxDate: this.maxDate,
            clearButton: true,
            nowButton: true,
            cancelText: '取消',
            okText: '确定',
            clearText: '清除',
            nowText: '今日'
        }).change(e => {
            // Provides two-way bind support on selectedValue property, I have to have an input property called selectedValue,
            // and an output property called selectedValueChange.
            this.selectedValue = e.target.value;
            this.selectedValueChange.emit(this.selectedValue);
        });
    }

    private generatePanelBodyId(identifier: string): string {
        return `${identifier}-${this.commonService.getCurrentTimestamp()}-${this.commonService.getRandomNumberWithinRange(100000, 999999)}`;
    }
}